package com.opensource.lzx.handler;

import com.alibaba.fastjson.JSON;
import com.opensource.lzx.cache.ServerManager;
import com.opensource.lzx.entity.ServerConfigEntity;
import com.opensource.lzx.proto.OperationType;
import com.opensource.lzx.proto.RequestContext;
import com.opensource.lzx.proto.ServiceRequest;
import com.opensource.lzx.proto.ServiceResponse;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.Locale;

public class DefaultBusinessHandler extends ChannelInboundHandlerAdapter {
    private static final String OS_NAME_WINDOWS = "windows";
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        RequestContext context = (RequestContext) msg;
        if (context.getRequest().getType().getNumber() == OperationType.REGISTER_REQUEST.getNumber()) {
            System.out.println("接收到客户端请求: " + JSON.toJSONString(context.getRequest()));
            ServiceRequest request = context.getRequest();

            RequestContext result;
            if (request.getOsName().toLowerCase(Locale.ROOT).startsWith(OS_NAME_WINDOWS)) {
                result = responseHandler(context.getRequest().getRequestId(), 500, "windows system can not support restart.");
            } else {
                ServerConfigEntity entity = new ServerConfigEntity();
                entity.setHost(request.getHost());
                entity.setPort(request.getPort());
                entity.setExecCommand(request.getExecCommand());
                entity.setSshUserName(request.getSshUsername());
                entity.setSshPassword(request.getSshPassword());
                ServerManager.registerHostInfo(ctx.channel().id().asLongText(), entity);
                result = responseHandler(context.getRequest().getRequestId(), 200, "host info register success.");
            }
            ctx.channel().writeAndFlush(result);
        } else {
            super.channelRead(ctx, msg);
        }
    }

    private RequestContext responseHandler(String requestId, int code, String msg) {
        ServiceResponse.Builder response = ServiceResponse.newBuilder();
        response.setCode(code)
                .setMessage(msg)
                .setRequestId(requestId)
                .setType(OperationType.REGISTER_RESPONSE);

        RequestContext.Builder result = RequestContext.newBuilder();
        result.setResponse(response.build());
        return result.build();
    }


}
